package com.issac.messagequeue.mqserver.datacenter;

import com.issac.messagequeue.mqserver.common.MqException;
import com.issac.messagequeue.mqserver.coreclass.Binding;
import com.issac.messagequeue.mqserver.coreclass.Exchange;
import com.issac.messagequeue.mqserver.coreclass.MSGQueue;
import com.issac.messagequeue.mqserver.coreclass.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 管理硬盘上的数据
 * 上层逻辑通过调用这个代码管理数据，不关心数据具体在内存or硬盘
 */
public class DiskDataCenter {
    // 管理数据库中数据
    private DataBaseManager dataBaseManager = new DataBaseManager();
    // 管理数据文件数据
    private MessageFileManager messageFileManager = new MessageFileManager();

    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    // 封装交换机操纵
    public void addExchange(Exchange exchange) {
        dataBaseManager.addExchange(exchange);
    }

    public void deleteExchange(String exchangeName) {
        dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> searchAllExchanges() {
        return dataBaseManager.searchAllExchanges();
    }

    // 封装队列操作
    public void addMSGQueue(MSGQueue queue) throws IOException {
        dataBaseManager.addQueue(queue);
        messageFileManager.createQueueFiles(queue.getName());
    }

    public void deleteMSGQueue(String queueName) throws IOException {
        dataBaseManager.deleteQueue(queueName);
        messageFileManager.destroyQueueFiles(queueName);
    }

    public List<MSGQueue> searchAllMSGQueues() {
        return dataBaseManager.searchAllQueues();
    }

    // 封装绑定操作
    public void addBinding(Binding binding) {
        dataBaseManager.addBinding(binding);
    }

    public void deleteBinding(Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> searchAllBindings() {
        return dataBaseManager.searchAllBindings();
    }

    // 封装消息操作
    public void sendMessage(Message message, MSGQueue queue) throws IOException, MqException {
        messageFileManager.sendMessage(message, queue);
    }

    public void deleteMessage(Message message, MSGQueue queue) throws IOException, ClassNotFoundException, MqException {
        messageFileManager.deleteMessage(queue, message);
        // GC
        if (messageFileManager.checkGC(queue.getName())) {
            messageFileManager.gc(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, MqException, ClassNotFoundException {
        return messageFileManager.loadAllMsgFromQueue(queueName);
    }
}
